//
//  DataBase.m
//  wdawdawdw
//
//  Created by 吕超 on 16/11/17.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "DataBase.h"
#import "FMDB.h"
#import "LXModel.h"

static DataBase *ShareDB = nil;


@interface DataBase ()

@property (nonatomic, strong)FMDatabase *db;


@end

@implementation DataBase

+ (instancetype)ShareDataBase{
    static dispatch_once_t  onceToKen;
    dispatch_once(&onceToKen,^{
        if (ShareDB == nil) {
            ShareDB = [[DataBase alloc]init];
            [ShareDB initDataBase];
        }
    });
    return ShareDB;
}



// 重写 allocWithZone   保证单例 唯一性
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    if(ShareDB == nil){
        ShareDB = [super allocWithZone:zone];
    }
    return ShareDB;
}

- (id)copyWithZone:(NSZone *)zone{
    return self;
}


- (void)initDataBase{
    // 获得Documents目录路径
    
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    // 文件路径   数据库 名
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"GWCmodel.sqlite"];
    
    
    // 实例化FMDataBase对象
    // 得到数据库
    self.db = [FMDatabase databaseWithPath:filePath];
    
    //打开数据库
    if ([_db open]){
     
        
        // 创建数据库  id 主键 自增   网易新闻字符串  商品选中数量  价格   图片
        BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shopping (id integer PRIMARY KEY AUTOINCREMENT,WYString text NOT NULL,Numer text NO NULL , Price integer NOT NULL , Picture blob NO NULL);"];
        if(result){
            NSLog(@"创表成功");
            //一定要使用缓存，减少时间复杂度
            [_db shouldCacheStatements];
            
        }else{
            NSLog(@"创表失败");
        }
        
    }
}



// 插入 数据
- (void)addDataBase:(LXModel *)model{
    // 打开数据库
    [_db open];
    
    //  根据  字符串 判断数据库中是否存在
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_shopping where WYString = ?",model.alias];
    
    //2 遍历结果
    if([resultSet next]){

    // SET 更新内容   WHERE  判断条件   如果model.number 即数量不一样  就更新
       [_db executeUpdate:@"UPDATE t_shopping SET Numer = ?  WHERE WYString = ? ",model.number,model.alias];

    }else {
        // 不存在  插入新数据
        
     BOOL bResult =   [_db executeUpdateWithFormat:@"INSERT INTO t_shopping (WYString,Numer,Price,Picture) VALUES (%@ ,%@ ,%ld,%@);",model.alias,model.number,model.DanGeJiaGe,model.picture];
    
        if(bResult) {
            NSLog(@"数据插入成功！");
        }
        else {
            NSLog(@"数据插入失败！");
        }
    }
}




//删除 数据
- (void)deleteDataBase:(LXModel *)model{
    
    [_db open];
    // 根据 网易字符串  判断
    [_db executeUpdate:@"DELETE FROM t_shopping WHERE WYString = ?",model.alias];
}



// 获取所有数据
- (NSMutableArray *)getAllData{
    [_db open];
    
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    
    FMResultSet *res = [_db executeQuery:@"SELECT * FROM t_shopping"];
    
    while ([res next]) {
        LXModel *model = [[LXModel alloc] init];
        
        model.alias = [res stringForColumn:@"WYString"];

        model.DanGeJiaGe = [[res stringForColumn:@"Price"]integerValue];
        
        model.number = [res stringForColumn:@"Numer"] ;
        
        model.picture = [res dataForColumn:@"Picture"];
 
        
        [dataArray addObject:model];
    
    }
    return dataArray;
}



@end
